package com.czf.testmodule.io.nio;


import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.Scanner;

/**
 * @author zfChen
 * @create 2022/6/14 10:42
 */
//客户端案例实现-基于NIO非阻塞通信
public class Client {
    public static void main(String[] args) {
        try {
            //1.获取通道
            SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1",9999));
            //2.切换为非阻塞模式
            socketChannel.configureBlocking(false);
            //3.分配指定缓存区大小
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
            //4.发送数据给服务端
            Scanner scanner = new Scanner(System.in);
            while (true) {
                System.out.println("请输入：");
                String s = scanner.nextLine();
                byteBuffer.put(s.getBytes());
                byteBuffer.flip();
                socketChannel.write(byteBuffer);
                byteBuffer.clear();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
